<template>
  <div>
    <!-- 登录弹框 -->
    <el-dialog
      :visible.sync="loginDialogFormVisible"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="clearLogin"
      @open="handleLoginOpen"
      title="登录账号"
    >
      <!-- 密码登录 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="密码登录" name="1">
          <el-form
            :model="loginRuleForm"
            :rules="pwdLoginRules"
            ref="pwdLoginRef"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="loginRuleForm.username"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                :type="pwdLoginType"
                v-model="loginRuleForm.password"
                placeholder="请输入密码"
              >
                <el-button
                  v-if="pwdLoginEyeToggle"
                  slot="append"
                  class="iconfont icon-yanjing-biyan"
                  @click="handleShowLoginPwd"
                ></el-button>
                <el-button
                  v-else
                  slot="append"
                  class="iconfont icon-yanjing1"
                  @click="handleHideLoginPwd"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!-- 验证码登录 -->
        <el-tab-pane label="验证码登录" name="2">
          <el-form
            :model="loginRuleForm"
            :rules="codeLoginRules"
            ref="codeLoginRef"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="loginRuleForm.phone"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
              <el-input v-model="loginRuleForm.code" placeholder="请输入验证码">
                <template slot="append">
                  <el-button
                    type="primary"
                    v-if="captchaToggle"
                    @click.stop="countdown"
                    >发送验证码</el-button
                  >
                  <el-button v-else disabled>{{ countnum }} S</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          type="success"
          plain
          @click="handleRegisterDialog"
          style="margin-right: 30px"
          >没有账号？立即注册</el-button
        >
        <el-button @click="resetForm()">取 消</el-button>
        <el-button type="primary" @click="handleLogin">登 录</el-button>
        <el-button
          type="warning"
          plain
          @click="handleForgetPasswordDialog"
          style="margin-left: 40px"
          >忘记密码</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { mapState, mapMutations } from "vuex";

export default {
  components: {},
  data() {
    return {
      activeName: "1",
      pwdLoginEyeToggle: true,
      pwdLoginType: "password",
      loginRuleForm: {
        username: "",
        phone: "",
        password: "",
        code: "",
      },
      pwdLoginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      codeLoginRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: this.$reg.phone,
            message: "手机号格式有误！请重新输入",
            trigger: "change",
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            pattern: this.$reg.code,
            message: "请输入4位数字",
            trigger: "blur",
          },
        ],
      },
      countnum: 60, // 短信间隔时间
      captchaToggle: true,
    };
  },
  computed: {
    ...mapState([
      "isManageSystem",
      "loginDialogFormVisible",
      "registerDialogFormVisible",
      "forgetPasswordDialogFormVisible",
      "isCollapse",
    ]),
  },
  created() {},
  mounted() {},
  methods: {
    ...mapMutations([
      "changeManageSystem",
      "showLoginDialog",
      "hideLoginDialog",
      "showRegisterDialog",
      "hideRegisterDialog",
      "showForgetPasswordDialog",
      "hideForgetPasswordDialog",
    ]),
    // 忘记密码弹窗
    handleForgetPasswordDialog() {
      this.hideLoginDialog();
      this.showForgetPasswordDialog();
    },
    // 立即注册弹框
    handleRegisterDialog() {
      this.hideLoginDialog();
      this.showRegisterDialog();
    },
    // 弹框打开的回调
    handleLoginOpen() {
      this.loginRuleForm.username = window.sessionStorage.getItem("username");
      this.loginRuleForm.phone = window.sessionStorage.getItem("telephone");
    },
    // 点击登陆按钮
    handleLogin() {
      if (this.activeName == "1") {
        // 密码登录
        this.$refs.pwdLoginRef.validate(async (valid) => {
          if (valid) {
            axios
              .post(`${this.$server}/login`, {
                username: this.loginRuleForm.username,
                password: this.loginRuleForm.password,
                type: 1,
              })
              .then((response) => {
                // console.log(response, "密码登陆");
                if (response.data.code == 200) {
                  this.$message.success(response.data.msg);
                  this.hideLoginDialog();
                  if (
                    this.loginRuleForm.username == "admin" &&
                    this.loginRuleForm.password == "123"
                  ) {
                    this.changeManageSystem(true);
                    this.$router.push({ name: "manageSystemTicketInfo" });
                    window.sessionStorage.setItem(
                      "manageSystemUsername",
                      this.loginRuleForm.username
                    );
                    window.sessionStorage.removeItem("username");
                    window.sessionStorage.removeItem("telephone");
                    window.sessionStorage.removeItem("avatar");
                    return;
                  }
                  window.sessionStorage.setItem(
                    "username",
                    response.data.data.username
                  );
                  window.sessionStorage.setItem(
                    "telephone",
                    response.data.data.phone
                  );
                  window.sessionStorage.setItem(
                    "avatar",
                    response.data.data.avatar
                  );
                  location.reload();
                } else {
                  this.$message.error(response.data.msg);
                }
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else if (this.activeName == "2") {
        // 验证码登录
        this.$refs.codeLoginRef.validate(async (valid) => {
          if (valid) {
            var { data: verifycaptchaResult } = await axios.get(
              `${this.$server}/verifycaptcha`,
              {
                params: {
                  phone: this.loginRuleForm.phone,
                  captcha: this.loginRuleForm.code,
                  type: 2,
                },
              }
            );
            // console.log(verifycaptchaResult, "注册校验验证码结果");
            if (verifycaptchaResult.code == 200) {
              this.$message.success("登陆成功");
              this.hideLoginDialog();
              window.sessionStorage.setItem(
                "username",
                verifycaptchaResult.data.username
              );
              window.sessionStorage.setItem(
                "telephone",
                verifycaptchaResult.data.phone
              );
              window.sessionStorage.setItem(
                "avatar",
                response.data.data.avatar
              );
              location.reload();
            } else {
              this.$message.error(verifycaptchaResult.msg);
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
    // 发送验证码
    async sendCaptcha() {
      var { data: res } = await axios.get(`${this.$server}/sendcaptcha`, {
        params: {
          phone: this.loginRuleForm.phone,
          type: 2,
        },
      });
      // console.log(res);
      if (res.code == 200) {
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.msg);
      }
    },
    // 点击发送验证码按钮
    countdown() {
      if (
        this.loginRuleForm.phone &&
        this.$reg.phone.test(this.loginRuleForm.phone)
      ) {
        this.sendCaptcha();
        this.captchaToggle = false;
        var timer = setInterval(() => {
          if (this.countnum > 0) {
            this.countnum--;
            this.captchaToggle = false;
          } else {
            clearInterval(timer);
            timer = null;
            this.countnum = 60;
            this.captchaToggle = true;
          }
        }, 1000);
      } else {
        this.$message.error("请先输入正确的手机号");
      }
    },
    // 重置表单
    resetForm() {
      this.$refs.pwdLoginRef.resetFields();
      this.$refs.codeLoginRef.resetFields();
      this.hideRegisterDialog();
      this.hideLoginDialog();
    },
    // 清除登录表单数据
    clearLogin() {
      this.loginRuleForm = {
        username: "",
        phone: "",
        password: "",
        code: "",
      };
    },
    // 登陆密码框内容显隐
    handleShowLoginPwd() {
      this.pwdLoginType = "text";
      this.pwdLoginEyeToggle = false;
    },
    handleHideLoginPwd() {
      this.pwdLoginType = "password";
      this.pwdLoginEyeToggle = true;
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-dialog {
  height: max-content;
  padding: 30px;
  width: 40%;
}

::v-deep .el-dialog__header {
  text-align: center;
}
</style>
